<template>
  <div>
    <!-- 面包屑导航 -->
    <bread :item="['用户管理','用户列表']"></bread>

    
    <!-- 卡片视图 -->
    <el-card shadow="hover" class="box-card" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" 
                    v-model="queryInfo.query" 
                    clearable @clear="getUsers" 
                    class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" >
          <el-button type="primary" @click="showDialog= true">添加用户</el-button>
        </el-col> 
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="users" stripe border height="480">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-switch :key="scope.row.id" @change="stateChanged(scope.row,$event)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175">
          <template slot-scope="scope">
            <!-- 添加操作 -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDia(scope.row.id)"></el-button>       
            <!-- 提示信息 -->
            <el-tooltip class="item" effect="dark " :enterable="false" content="分配角色" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip> 
            <!-- 删除     -->
             <el-button size="mini" type="danger" icon="el-icon-delete" 
                        @click="removeUserById(scope.row.id)"  ></el-button> 
            
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
       <el-pagination @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="queryInfo.pagenum"
                      :page-sizes="[5, 10, 20]" background
                      :page-size="queryInfo.pagesize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total">
       </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
 <el-dialog  :visible.sync="showDialog"
            width="50%" title="添加用户" @close="closeDialog">
   <!-- 数据收集 -->
  <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username" :disabled="NBtn"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password" :disabled="NBtn"></el-input>
    </el-form-item> 
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="addForm.mobile" :disabled="NBtn"></el-input>
    </el-form-item> 
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email" :disabled="NBtn"></el-input>
    </el-form-item> 
  </el-form>
  <!-- 底部按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="showDialog = false" :disabled="NBtn">取 消</el-button>
    <el-button type="primary" @click="addUser" :disabled="NBtn">确 定</el-button>
  </span>
 </el-dialog>

  <!-- 修改用户对话框 -->
  <el-dialog :visible.sync="editDialog"
   width="50%" title="提示" @close="editDialogClose">
  <!-- 内容显示 -->
    <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="70px">
      <el-form-item label="用户名" >
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile" >
        <el-input v-model="editForm.mobile" :disabled="NBtn"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" :disabled="NBtn"></el-input>
      </el-form-item>
    </el-form>
  <!-- 底部按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialog = false" :disabled="NBtn">取 消</el-button>
    <el-button type="primary" @click="editUserInfo" :disabled="NBtn">确 定</el-button>
  </span>
</el-dialog>

<!-- 分配角色对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRoleDia"
  width="50%" @close="setRoleColse">

  <div>
    <p>当前用户: {{userInfo.username}}</p>
    <p>当前角色: {{userInfo.role_name}}</p>
  </div>
  <el-select v-model="selectedRole" :disabled="NBtn"  placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDia = false" :disabled="NBtn">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo" :disabled="NBtn">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
import {bread} from "tools"
export default {
  components:{bread}
 ,data(){
    
    let chekmo=(rule,value,hook)=>{
      if(isNaN(value))return hook(new Error('只能是数字!'))
      if(value.length<6) return hook(new Error('必须大于6位数!'))
      return hook()
    }
    
    return{
    queryInfo:{
      query:""
      //当前页
     ,pagenum:1
     ,pagesize:5
    }
   ,users:[]
   ,total:0
   ,loading:true
   ,NBtn:false
   //添加用户
   ,showDialog:false
   //修改用户数据
   ,editDialog:false
   //分配角色
   ,setRoleDia:false
   //输入的数据
   ,addForm:{
     username:""
    ,password:""
    ,email:""
    ,mobile:""
   }
   //验证规则
   ,rules:{
     username:[
       {required:true,message:'请输入用户名',trigger:"blur"}
      ,{min:3, max:10, message:"长度在 3 到 10 个字符!", trigger:'blur'}
     ]
    ,password:[
       {required: true, message:'请输入用户密码!', trigger:'blur'}
      ,{min:6, max:15, message:"长度在 6 到 15 的字符!", trigger:"blur"}
     ]
    ,mobile:[
       {required: true, message:'请输入用户手机号!', trigger:'blur'}
      ,{validator:chekmo,trigger:'change'}  
     ]
    ,email:[
      { required: true, message: '请输入邮箱地址！', trigger: 'blur' }
     ,{ type: 'email', message: '请输入正确的邮箱地址！', trigger: ['blur', 'change'] }
    ]
   }
   //查询到的用户信息
   ,editForm:{}
   ,editRules:{
     mobile:[
       {required: true, message:'请输入用户手机号!', trigger:'blur'}
      ,{validator:chekmo,trigger:'change'}
     ]
    ,email:[
      { required: true, message: '请输入邮箱地址！', trigger: 'blur' }
     ,{ type: 'email', message: '请输入正确的邮箱地址！', trigger: ['blur', 'change'] }
    ]
   }
   //需要被分配角色的用户信息
   ,userInfo:{}
   //所有角色
   ,roleList:[]
   //选中的角色id
   ,selectedRole:''
   ,loading:false
  }}
 ,created(){
  this.getUsers()
 }
 ,methods:{
   async getUsers(){
     //发起请求
     let {data:ret}= await this.$XHR.get("users",{params:this.queryInfo})
     //提示获取失败
     if(ret.meta.status!==200) return this.$message({
       type:"error"
      ,message:"获取用户失败"
      ,center:"center"
     })
     //保存请求的数据
     this.users=ret.data.users
     this.total= ret.data.total
     return
   }
  ,async handleSizeChange(ns){
    this.loading= true
    this.queryInfo.pagesize=ns
    await this.getUsers()
    this.$nextTick(()=>{
      this.loading= false
    })
  }
  ,async handleCurrentChange(np){
    this.loading= true
    this.queryInfo.pagenum=np
    await this.getUsers()
    this.$nextTick(()=>{
      this.loading= false
    })
  }
  //监听开关
  ,async stateChanged(s,n){
    let {data:ret}= await this.$XHR.put(`/users/${s.id}/state/${n}`)
    let [type,message]=["success",n?"开启成功":"关闭成功"]
    if(ret.meta.status!==200){
      s.mg_state= !s.mg_state;
      [type,message] = ["error",n?"开启成功":"关闭失败"]
    }
    return this.$message({type,message,center:"center"})
  }
 ,closeDialog(){
   this.$refs['addForm'].resetFields()
  }
 ,addUser(){
  //  禁用按钮
   this.NBtn= true
   this.$refs['addForm'].validate(async valid=>{
     if(!valid) return this.NBtn=false
     //发起添加用户请求
     const {data:ret}= await this.$XHR.post('users',this.addForm)
     let [type,message]=['success',"添加成功"]
     if(ret?.meta?.status!==201){
       [type,message]=["error","添加失败"]
     }
     //提示信息
     this.$message({
       type
      ,message
      ,center:"center"
      ,duration:1800
     })
     
     setTimeout(()=>{
       //关闭对话框
       this.showDialog= false
       //启用按钮
       this.NBtn=false
     },1500)
    //刷新数据
    this.getUsers()
   })
  }
  //显示编辑对话框
 ,async showEditDia(n){
   //发送请求
   const {data:ret}= await this.$XHR.get('users/'+n)
  //提示错误信息并退出
   if(ret?.meta?.status!==200)return this.$message({type:"error",message:"获取失败",center:"center"})
  //显示对话框
   this.editDialog= true
   this.editForm= ret?.data ?ret?.data:{}

 }
 //监听修改对话框关闭
 ,editDialogClose(){
  //  this.$refs['editForm'].resetFields()
 }
 ,editUserInfo(){
   this.NBtn=true
   //表单提交的预校验
   this.$refs['editForm'].validate(async valid=>{
     if(!valid)return 
     //修改的请求
     let {email,mobile,id}=this.editForm
     let {data:ret}= await this.$XHR.put("users/"+id,{email,mobile})
     let [type,message,center]=["success","修改成功","center"]
     if(ret.meta.status!==200){
       [type,message]=["error","修改失败"]
       this.NBtn= false
     };
     //提示消息
    this.$message({type,message,center})
    if(type.length>6){
      //关闭对话框
      setTimeout(()=>{this.editDialog=false;this.NBtn= false},1800)
      //刷新用户列表
      this.getUsers()
     } 
   })
 }
 //监听删除按钮
 ,removeUserById(n){
   let [type,message,center]= ['success',"删除成功","center"]
   //删除确认
   this.$confirm('这将会永久删除此用户','提示',{
     confirmButtonText:"确认"
    ,cancelButtonText:"取消"
    ,type:"warning"
   })
   .then(async ()=>{
     //发送删除请求
     let {data:ret}= await this.$XHR.delete('users/'+n)
     if(ret.meta.status!==200){
       [type,message]=['error','删除失败!']
       return
     }
     //如果当前只有一位用户，删除时获取上一页数据
     if(this.users.length===1)this.queryInfo.pagenum--
     this.getUsers()
   },e=>{
     //取消时修改提示消息
     return [type,message]=[null,"已取消删除"]
   })
   .finally(h=>{
     //提示消息
     let all=type?{type}:{}
     all.message=message
     all.center=center
     this.$message(all)   
   })
  }
 ,async setRole(n){
   this.userInfo= n
  //获取所有角色列表
  let {data:ret}=await this.$XHR.get('roles')
  if(ret?.meta?.status!==200)return this.$message({type:"error",message:"获取失败",center:"center"})
  this.roleList= ret.data ? ret.data : []
   this.setRoleDia= true
   
 }
 ,async saveRoleInfo(){
   this.NBtn=true
   if(!this.selectedRole){
      this.NBtn= false
      return this.$notify({type:"warning",title:"提示",message:"请选择要分配的角色"})
   }
   let{data:ret}=await this.$XHR.put('users/'+this.userInfo.id+'/role',{rid:this.selectedRole})
   let [type,message,center]=["success","设置成功","center"]
   if(ret?.meta?.status!==200){[type,message]=["error","设置失败"];this.NBtn=false}
   setTimeout(()=>{
     this.$message({type,message,center,duration:1300})
     type!=="error" && setTimeout(()=>{
       this.setRoleDia=false
       this.NBtn= false
     },800)
     this.getUsers()
   },800)
 }
 ,setRoleColse(){
   this.selectedRole=''
   this.userInfo={}
 }
 }
}

</script>

<style lang="less" scoped>

.el-table{
  margin-top: 15px;
  font-size: 13px;
}
.el-pagination{
  margin-top: 15px;
}
</style>